//
//  CommodityTitleView.m
//  yunbaolive
//
//  Created by ybRRR on 2020/2/24.
//  Copyright © 2020 cat. All rights reserved.
//

#import "CommodityTitleView.h"
#import "YBImageView.h"
#import "ShowDetailVC.h"
@implementation CommodityTitleView

-(instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = UIColor.whiteColor;
        imageArray = [NSMutableArray array];
        _newvideoPath = @"";
        [self createUI];
    }
    return self;
}
-(void)createUI{
    UILabel*title = [[UILabel alloc]init];
    title.frame = CGRectMake(12, 10, 180, 20);
    title.font = [UIFont boldSystemFontOfSize:14];
    title.text = YZMsg(@"商品标题");
    title.textColor = [UIColor blackColor];
    [self addSubview:title];

    self.titleText = [[UITextField alloc]init];
    self.titleText.frame = CGRectMake(12, title.bottom+10, _window_width-24, 20);
    self.titleText.font = [UIFont systemFontOfSize:14];
    self.titleText.textColor = [UIColor blackColor];
    self.titleText.backgroundColor = [UIColor clearColor];
    self.titleText.returnKeyType = UIReturnKeyDone;
    self.titleText.delegate = self;
    [self.titleText addTarget:self action:@selector(titleTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    NSMutableAttributedString*holderString = [[NSMutableAttributedString alloc] initWithString:YZMsg(@"建议填写产品词、属性词、营销词等，不超过15个字") attributes:@{NSForegroundColorAttributeName:[UIColor grayColor] }];
    self.titleText.attributedPlaceholder = holderString;

    [self addSubview:self.titleText];
    
    imgWidth = (_window_width - 75)/4;

    videoBtn = [UIButton buttonWithType:0];
    videoBtn.frame = CGRectMake(15, self.titleText.bottom+15, imgWidth, imgWidth);
    videoBtn.backgroundColor = RGB(245, 245, 245);// RGB_COLOR(@"#302D41", 1);
    [videoBtn addTarget:self action:@selector(imageBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    videoBtn.tag = 1000;
    [videoBtn setImage:[UIImage imageNamed:@"addComm"] forState:0];
    [videoBtn setTitle:YZMsg(@"商品视频") forState:0];
    [videoBtn setTitleColor:[UIColor grayColor] forState:0];
    videoBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    videoBtn = [PublicObj setUpImgDownText:videoBtn];
    [self addSubview:videoBtn];
    
    imgeBtn = [UIButton buttonWithType:0];
    imgeBtn.frame = CGRectMake(15+(1%4)*(imgWidth + 15), self.titleText.bottom+15, imgWidth, imgWidth);
    imgeBtn.backgroundColor = RGB(245, 245, 245);// RGB_COLOR(@"#302D41", 1);
    [imgeBtn addTarget:self action:@selector(imageBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [imgeBtn setImage:[UIImage imageNamed:@"addComm"] forState:0];
    [imgeBtn setTitle:YZMsg(@"商品图") forState:0];
    [imgeBtn setTitleColor:[UIColor grayColor] forState:0];
    imgeBtn.titleLabel.font = [UIFont systemFontOfSize:10];
    imgeBtn = [PublicObj setUpImgDownText:imgeBtn];
    imgeBtn.tag = 1001;
    [self addSubview:imgeBtn];
}
- (void)imageBtnClick:(UIButton *)sender{
    if (sender.tag == 1001) {
        TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:9-imageArray.count delegate:self];
        imagePC.preferredLanguage = [lagType isEqual:ZH_CN] ? @"zh-Hans":@"en";
        imagePC.modalPresentationStyle = 0;
        imagePC.showSelectBtn = YES;
        imagePC.allowCrop = NO;
        imagePC.allowPickingOriginalPhoto = NO;
        imagePC.oKButtonTitleColorNormal = Pink_Cor;
        imagePC.allowTakePicture = YES;
        imagePC.allowTakeVideo = NO;
        imagePC.allowPickingVideo = NO;
        imagePC.allowPickingMultipleVideo = NO;
        [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:imagePC animated:YES completion:nil];
    }else if (sender.tag == 1000){
        BOOL isShowLive = [[NSUserDefaults standardUserDefaults]boolForKey:@"isShowChatLive"];
        if (isShowLive) {
            [MBProgressHUD showError:YZMsg(@"直播间开启期间不可使用该操作")];
            return;

        }

        TZImagePickerController *imagePC = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:self];
        imagePC.preferredLanguage = [lagType isEqual:ZH_CN] ? @"zh-Hans":@"en";
        imagePC.modalPresentationStyle = 0;
        imagePC.showSelectBtn = NO;
        imagePC.allowCrop = NO;
        imagePC.allowPickingOriginalPhoto = NO;
        imagePC.oKButtonTitleColorNormal = Pink_Cor;
        imagePC.allowPickingImage = NO;
        imagePC.allowTakePicture = NO;
        imagePC.allowTakeVideo = YES;
        imagePC.allowPickingVideo = YES;
        imagePC.allowPickingMultipleVideo = NO;
        imagePC.videoMaximumDuration = live_MAX_RECORD_TIME;
        [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:imagePC animated:YES completion:nil];
    }
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.titleText resignFirstResponder];
    return YES;
}
#pragma mark - UITextViewDelegate
-(void)titleTextFieldDidChange:(UITextField *)textField
{
    NSString *nameString;
    if (textField == self.titleText) {
        nameString = self.titleText.text;
    }
    NSString *lang = [[[UITextInputMode activeInputModes]firstObject] primaryLanguage]; // 键盘输入模式
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [self.titleText markedTextRange];//获取高亮部分
        UITextPosition *position = [self.titleText positionFromPosition:selectedRange.start offset:0];
        //没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            if (nameString.length > 15) {
                self.titleText.text = [nameString substringToIndex:15];
            }
        }else{
            //有高亮选择的字符串，则暂不对文字进行统计和限制
        }
    }else{
        // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
        if (nameString.length > 15) {
            self.titleText.text = [nameString substringToIndex:15];
        }
    }

}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(PHAsset *)asset {
    [MBProgressHUD showMessage:@""];
    [[TZImageManager manager] getVideoOutputPathWithAsset:asset presetName:AVAssetExportPresetMediumQuality success:^(NSString *outputPath) {
        NSLog(@"视频导出到本地完成,沙盒路径为:%@",outputPath);
        if (outputPath) {
            [MBProgressHUD hideHUD];
            self.videoPath = outputPath;
            self.newvideoPath = outputPath;
            self.videoCoverImage = coverImage;
            [self addVideoimage];
        }else{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:YZMsg(@"请重新选择(iCloud视频请先在本地相册下载后上传)")];
        }
    } failure:^(NSString *errorMessage, NSError *error) {
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:errorMessage];
        NSLog(@"视频导出失败:%@,error:%@",errorMessage, error);
    }];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    NSLog(@"------多选择图片--：%@",photos);
    [imageArray addObjectsFromArray:photos];
    [self.delegate setCommodityImg:imageArray];

    [self setImageFrame];
}
#pragma mark-----添加视频------------
-(void)addVideoimage{
    subVideoBtn = [UIButton buttonWithType:0];
    subVideoBtn.frame = CGRectMake(0, 0, videoBtn.width, videoBtn.height);
    if ([self.fromStr isEqual:@"seller"]) {
        [subVideoBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:self.goodsModel.video_thumb_format] forState:0];
    }else{
        [subVideoBtn setBackgroundImage:self.videoCoverImage forState:0];
    }
    subVideoBtn.contentMode =  UIViewContentModeScaleAspectFill;
    subVideoBtn.clipsToBounds = YES;

    [subVideoBtn setImage:[UIImage imageNamed:@"evaluate_播放"] forState:0];
    [subVideoBtn addTarget:self action:@selector(showVideo) forControlEvents:UIControlEventTouchUpInside];
    [videoBtn addSubview:subVideoBtn];
    
    UIButton *delBtn = [UIButton buttonWithType:0];
    delBtn.frame = CGRectMake(subVideoBtn.width-25, 5, 20, 20);
    [delBtn setBackgroundImage:[UIImage imageNamed:@"comm_del"] forState:0];
    [delBtn addTarget:self action:@selector(delVideoClick) forControlEvents:UIControlEventTouchUpInside];
    [subVideoBtn addSubview:delBtn];

}
#pragma mark-------预览图片------------
-(void)showImage:(UIButton *)sender{
    NSInteger index = sender.tag-3000-1;
    YBImageView *imgView = [[YBImageView alloc] initWithImageArray:imageArray andIndex:index andMine:NO isDtCell:NO andBlock:^(NSArray * _Nonnull array) {
    }];
    [imgView hideDelete];
    [[UIApplication sharedApplication].keyWindow addSubview:imgView];
}
#pragma mark-------预览视频------------
-(void)showVideo{
    ShowDetailVC *detail = [[ShowDetailVC alloc]init];
    detail.videoPath =self.videoPath;
    detail.deleteEvent = ^(NSString *type) {
    };
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:detail animated:NO];
}
#pragma mark-------删除视频------------
-(void)delVideoClick{
    self.videoPath = @"";
    [subVideoBtn removeFromSuperview];
    subVideoBtn = nil;
}

#pragma mark-------删除图片------------
-(void)delImageClick:(UIButton *)sender{
    NSInteger index = sender.tag-4000-1;
    [imageArray removeObjectAtIndex:index];
    [self.delegate setCommodityImg:imageArray];
    [self setImageFrame];
}
#pragma mark-------重新赋值图片坐标----------
-(void)setImageFrame{
    for (UIButton *btn in self.subviews) {
        if (btn.tag >=3000) {
            [btn removeFromSuperview];
        }
    }
    if (imageArray.count > 0) {
        
        if (imageArray.count < 3) {
            self.heightEvent(170);
        }else if (imageArray.count>=3 && imageArray.count< 7){
            if (self.heightEvent) {
                self.heightEvent(170+imgWidth+15);
            }
        }else if(imageArray.count >= 7){
            if (self.heightEvent) {
                self.heightEvent(170+imgWidth*2+30);
            }
        }
        for (int i = 1; i <= imageArray.count ; i ++) {
            UIButton *btn = [UIButton buttonWithType:0];
            btn.imageView.contentMode = UIViewContentModeScaleAspectFill;
            btn.imageView.clipsToBounds = YES;
            btn.backgroundColor = RGB(250, 250, 250);
            if (i < 4) {
                btn.frame = CGRectMake(15+(i%4)*(imgWidth + 15), self.titleText.bottom+15, imgWidth, imgWidth);
            }else  if (i >= 4 && i < 8){
                btn.frame = CGRectMake(15+(i%4)*(imgWidth + 15), self.titleText.bottom+15+(imgWidth+15), imgWidth, imgWidth);
            }else{
                btn.frame = CGRectMake(15+(i%4)*(imgWidth + 15), self.titleText.bottom+15+imgWidth*2+30, imgWidth, imgWidth);
            }
            btn.tag = 3000+i;
            //如果是编辑图片需要赋值判断：判断图片类型：UIImage或网络图片
            if ([self.fromStr isEqual:@"seller"]) {
                if ([imageArray[i-1] isKindOfClass:[UIImage class]]) {
                    [btn setImage:imageArray[i-1] forState:0];
                }else{
                    [btn sd_setImageWithURL:[NSURL URLWithString:imageArray[i-1]] forState:0];
                }
            }else{
                [btn setImage:imageArray[i-1] forState:0];
            }
            [btn addTarget:self action:@selector(showImage:) forControlEvents:UIControlEventTouchUpInside];
            [self addSubview:btn];
            
            UIButton *delBtn = [UIButton buttonWithType:0];
            delBtn.frame = CGRectMake(imgWidth-25, 5, 20, 20);
            [delBtn setBackgroundImage:[UIImage imageNamed:@"comm_del"] forState:0];
            delBtn.tag = 4000+i;
            [delBtn addTarget:self action:@selector(delImageClick:) forControlEvents:UIControlEventTouchUpInside];
            [btn addSubview:delBtn];
        }
    }else{
        self.heightEvent(170);
        imgeBtn.frame = CGRectMake(15+(1%4)*(imgWidth + 15), self.titleText.bottom+15, imgWidth, imgWidth);
        [imgeBtn setTitle:YZMsg(@"商品图") forState:0];
        return;
    }
    if (imageArray.count == 9) {
        imgeBtn.hidden = YES;
    }else{
        imgeBtn.hidden = NO;
        imgeBtn.frame = CGRectMake(15+((imageArray.count+1)%4)*(imgWidth + 15), self.titleText.bottom+((imageArray.count+1)/4)*(imgWidth + 15)+15, imgWidth, imgWidth);
        [imgeBtn setTitle:[NSString stringWithFormat:@"%ld/9",imageArray.count] forState:0];
        imgeBtn = [PublicObj setUpImgDownText:imgeBtn];
    }
}
#pragma mark--------编辑商品赋值-----------------
-(void)setDetaiModelData:(CommodityDetailModel *)detailModel fromWhere:(NSString *)from
{
    _goodsModel = detailModel;
    self.fromStr = from;
    //有视频
    if (detailModel.video_thumb_format.length > 5) {
        [self addVideoimage];
        self.videoPath = detailModel.video_url_format;
    }
    //有图片
    if (detailModel.thumbs_format.count > 0) {
        [imageArray addObjectsFromArray:detailModel.thumbs_format];
        [self setImageFrame];
        [self.delegate setCommodityImg:imageArray];
    }
}

@end
